package com.chen.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.entity.Skus;
import com.chen.entity.User;
import com.chen.mapper.SkusMapper;
import com.chen.mapper.UserMapper;
import com.chen.service.SkusService;
import com.chen.service.TokenService;
import com.chen.utils.JWTUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author cws
 * @since
 */
@Service
public class TokenServiceImpl  extends ServiceImpl<UserMapper, User> implements TokenService {
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @Resource
    UserMapper userMapper;

    //    校验
    @Override
    public User checkToken(String token) {
        if(StringUtils.isBlank(token)){
            return null;
        }
        //        解析
        Map<String, Object> stringObjectMap = JWTUtils.checkToken(token);
//      失败
        if (stringObjectMap == null) {
            return null;
        }
//    成功再去查redis是否存在
        String userToken = redisTemplate.opsForValue().get("TOKEN_" + token);
        if(userToken==null){
            return null;
        }
        User sysUser = JSON.parseObject(userToken, User.class);
        return sysUser;
    }

    @Override
    public User refreshToken(String token) {
        if(StringUtils.isBlank(token)){
            return null;
        }
        Long userId = JWTUtils.getUserId(token);
        User user = userMapper.selectById(userId);
        String key = "TOKEN_" + token;
//        重新赋值
        redisTemplate.opsForValue().set(key,JSON.toJSONString(user));
        return user;
    }
}

